<!-- 系统用户 -->
<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"
import type { UserData } from "./apis/type"
import { validateUniqueField } from "@@/composables/useFormValidate"
import { useFullscreen } from "@@/composables/useFullscreen"
import { usePagination } from "@@/composables/usePagination"
import { useTableSort } from "@@/composables/useTableSort"
import { checkPermission } from "@@/utils/permission"
import { CirclePlus, Close, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
import * as UserApi from "./apis"

defineOptions({
  // 命名当前组件: 系统欧诺个户
  name: "SysUser"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const { sortColumn, sortOrder, handleSortChange } = useTableSort({})
// 编辑弹窗是否全屏
const { isFullscreen, fullscreenSvgName, toggleFullscreen } = useFullscreen()

// #region 增
const DEFAULT_FORM_DATA: UserData = {
  phone: "",
  email: "",
  enable: true, // 默认启用
  username: "",
  nickname: "",
  password: "", // 可选字段需初始化
  gender: 0, // 默认性别值
  birthday: "" // 或默认日期如 '2000-01-01'
}

const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<UserData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<UserData> = {
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }, { validator: validateUniqueField("/system/user/check", "username", "用户名", formData), trigger: "blur" }],
  phone: [{ required: true, trigger: "blur", message: "请输入手机号" }, { validator: validateUniqueField("/system/user/check", "phone", "手机号码", formData), trigger: "blur" }],
  email: [{ required: true, trigger: "blur", message: "请输入邮箱" }, { validator: validateUniqueField("/system/user/check", "email", "Email", formData), trigger: "blur" }]
}
function handleCreateOrUpdate() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    loading.value = true
    UserApi.saveUser(formData.value).then(() => {
      ElMessage.success("操作成功")
      dialogVisible.value = false
      getTableData()
    }).finally(() => {
      loading.value = false
    })
  })
}
function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
// #endregion

// #region 删
function handleDelete(row: UserData) {
  if (!row.id) return
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    UserApi.deleteUser(row.id!).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
// #endregion

// #region 改
function handleUpdate(row: UserData) {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
// #endregion

// #region 查
const tableData = ref<UserData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  username: "",
  phone: "",
  email: "",
  nickname: ""

})
function getTableData() {
  loading.value = true
  UserApi.queryUserPage({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    sortColumn: sortColumn.value,
    sortOrder: sortOrder.value,
    ...searchData
  }).then(({ data }) => {
    paginationData.total = data.total
    tableData.value = data.datas
    console.log(tableData.value)
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}

function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
// #endregion

// #region 更新用户状态
function updateEnable(row: UserData) {
  const id = row.id
  if (!id) return
  const enbale = row.enable
  const text = enbale ? "禁用" : "启用"
  ElMessageBox.confirm(`确认${text}用户吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    UserApi.updateUserEnable(id, !enbale).then(() => {
      ElMessage.success("修改成功")
      getTableData()
    })
  })
}
// #endregion

// #region 修改用户密码
const updatePasswordDialogVisible = ref(false)
const passwordFormRef = ref<FormInstance | null>(null)

function handleUpdatePassword(row: UserData) {
  updatePasswordDialogVisible.value = true
  formData.value = cloneDeep(row)
}
function resetPasswordForm() {
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
function updatePassword(row: UserData) {
  const id = row.id
  const password = row.password
  if (!id || !password) return
  ElMessageBox.confirm(`确认修改${row.nickname}的密码吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    UserApi.updatePassword(id, password).then(() => {
      ElMessage.success("修改成功")
      updatePasswordDialogVisible.value = false
      getTableData()
    })
  })
}
// #endregion

// 监听分页参数的变化
watch([
  () => paginationData.currentPage,
  () => paginationData.pageSize,
  () => sortColumn.value,
  () => sortOrder.value
], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="searchData.username" placeholder="请输入" />
        </el-form-item>

        <el-form-item prop="nickname" label="昵称">
          <el-input v-model="searchData.nickname" placeholder="请输入" />
        </el-form-item>

        <el-form-item prop="phone" label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="searchData.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
            新增用户
          </el-button>
          <!-- <el-button type="danger" :icon="Delete">
            批量删除
          </el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" size="small" @sort-change="handleSortChange" stripe>
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="username" label="用户名" align="center" sortable="custom" />
          <el-table-column prop="nickname" label="昵称" align="center" />
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column prop="email" label="邮箱" align="center" />
          <el-table-column prop="enable" label="状态" align="center" sortable="custom">
            <template #default="scope">
              <el-tag v-if="scope.row.enable" type="success" effect="plain" disable-transitions>
                启用
              </el-tag>
              <el-tag v-else type="danger" effect="plain" disable-transitions>
                禁用
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column fixed="right" label="操作" width="280" align="center">
            <template #default="scope">
              <el-button-group>
                <el-button
                  :type="scope.row.enable ? 'danger' : 'success'" text bg size="small"
                  v-if="checkPermission(['admin'])" @click="updateEnable(scope.row)"
                >
                  {{ scope.row.enable ? '禁用' : '启用'
                  }}
                </el-button>
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">
                  修改
                </el-button>
                <el-button type="warning" text bg size="small" @click="handleUpdatePassword(scope.row)">
                  设置密码
                </el-button>
                <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
          :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增 编辑 start  -->
    <el-dialog v-model="dialogVisible" @closed="resetForm" width="50%" :fullscreen="isFullscreen" :show-close="false">
      <!-- 自定义标题样式 -->
      <template #header>
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <div style="display: flex; align-items: center;">
            <el-icon style="margin-right: 8px;">
              <Edit />
            </el-icon>
            <span style="font-size: 18px; font-weight: bold;"> {{ formData.id === undefined ? '新增用户' : '修改用户' }}</span>
          </div>
          <!-- 右侧按钮组 -->
          <div style="display: flex; align-items: center;">
            <!-- 全屏按钮 -->
            <el-button type="text" @click="toggleFullscreen">
              <SvgIcon :name="fullscreenSvgName" class="svg-icon" />
            </el-button>
            <!-- 自定义关闭按钮 -->
            <el-button type="text" @click="dialogVisible = false" :icon="Close" />
          </div>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
        <!-- username 和 nickname -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="username" label="用户名" label-width="100px">
              <el-input v-model="formData.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="nickname" label="昵称" label-width="100px">
              <el-input v-model="formData.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 电话号码 和 email -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="phone" label="手机号" label-width="100px">
              <el-input v-model="formData.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="email" label="Email" label-width="100px">
              <el-input v-model="formData.email" placeholder="请输入Email" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 状态和任务类型 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="gender" label="性别" label-width="100px">
              <el-select v-model="formData.gender" clearable placeholder="请选择性别">
                <el-option label="保密" :value="0" />
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="enable" label="状态" label-width="100px">
              <el-select v-model="formData.enable" clearable placeholder="请选择状态">
                <el-option label="启用" :value="true" />
                <el-option label="禁用" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 生日 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="birthday" label="生日" label-width="100px">
              <el-date-picker
                v-model="formData.birthday" type="date" placeholder="生日" value-format="YYYY-MM-DD"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">
          确认
        </el-button>
      </template>
    </el-dialog>
    <!-- 新增 编辑 end -->

    <!-- 设置密码 start -->
    <el-dialog v-model="updatePasswordDialogVisible" title="设置密码" width="30%" @closed="resetPasswordForm">
      <el-form ref="passwordFormRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="username" label="用户名">
          {{ formData.username }} - {{ formData.nickname }}
        </el-form-item>
        <el-form-item v-if="formData.id !== undefined" prop="password" label="密码">
          <el-input v-model="formData.password" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updatePasswordDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="updatePassword(formData)">
          确认
        </el-button>
      </template>
    </el-dialog>
    <!-- 设置密码 end -->
  </div>
</template>

<style lang="scss" scoped>
.el-alert {
  margin-bottom: 20px;
}

.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
